package cn.cloud9.opencloud.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.text.StringEscapeUtils;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author OnCloud9
 * @description
 * @project Open-Cloud
 * @date 2022年04月16日 21:15
 */
public class EncodeUtil {

    private EncodeUtil(){}

    /**
     * 转义成安全的HTML字符
     * @param source
     * @return
     */
    public static String encodeHTML(String source) {
        return StringEscapeUtils.escapeHtml4(source);
    }

    /**
     * 转义回可以渲染的HTML字符？
     * @param encodeSource
     * @return
     */
    public static String decodeHTML(String encodeSource) {
        return StringEscapeUtils.unescapeHtml4(encodeSource);
    }

    /**
     * json格式编码处理
     * @param jsonObject
     * @param ignoreKeys
     */
    public static void encodeJsonObject(JSONObject jsonObject, String[] ignoreKeys) {
        if (jsonObject == null) return;
        final Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
        final Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            final Map.Entry<String, Object> next = iterator.next();
            final String key = next.getKey();
            final boolean hasMatch = Arrays.asList(ignoreKeys).stream().anyMatch(ignoreKey -> ignoreKey.contains(key));
            if (hasMatch) return;

            final Object value = next.getValue();
            if (value instanceof String) next.setValue( encodeHTML( String.valueOf( value)));
            else if (value instanceof JSONObject) encodeJsonObject( (JSONObject) value, ignoreKeys);
            else if (value instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) value;
                jsonArray.forEach(arrValue -> {
                    if (arrValue instanceof String) next.setValue( encodeHTML( String.valueOf( arrValue)));
                    else if (arrValue instanceof JSONObject) encodeJsonObject( (JSONObject) arrValue, ignoreKeys);
                });
            }

        }
    }




}
